package com.so206.crond;

import com.so206.po.ProxyList;
import com.so206.po.SystemUser;
import com.so206.po.SystemWeb;
import com.so206.service.ProxyService;
import com.so206.service.UserService;
import com.so206.service.WebConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 代理数据生成
 */
@Component
public class ProxyDataManagerTask {

    private static final Logger logger = LoggerFactory.getLogger(ProxyDataManagerTask.class);

    @Autowired
    private UserService userService;

    @Autowired
    private ProxyService proxyService;

    @Autowired
    private WebConfigService webConfigService;

    public ProxyDataManagerTask() {
        logger.info("ProxyDataManagerTask Init...");
    }

    /**
     * 每分钟更新代理信息
     */
    @Async
    @Scheduled(cron = "0 */1 *  * * * ")
    public void timerToNow() {
        logger.info("当前时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        logger.info("开始更新代理信息...");
        SystemWeb config = webConfigService.find_by_id(1L);
        List<SystemUser> list = userService.find_user_list();
        if (list != null && list.size() > 0) {
            for (SystemUser systemUser : list) {
                ProxyList model = proxyService.find_proxy_by_uid(systemUser.getId());
                if (model == null) {
                    if (systemUser.getUserParent() == 0) {
                        ProxyList proxyList = new ProxyList();
                        proxyList.setOptTime(new Date());
                        proxyList.setCreateTime(new Date());
                        proxyList.setUid(systemUser.getId());
                        proxyList.setStaff(config.getProxyStaffBase());
                        proxyList.setStatus(0);
                        Long proxy = proxyService.save_proxy(proxyList);
                        logger.info("填充代理信息数据:用户PID:" + proxyList.getUid() + "代理数据ID:" + proxy);
                    } else {
                        logger.info("无代理权限:用户PID:" + systemUser.getId());
                    }
                } else {
                    logger.info("代理信息数据已存在:用户PID:" + model.getUid() + "代理数据ID:" + model.getId());
                }
            }
        }
        logger.info("更新代理信息完毕...");
    }


}
